﻿////////////////////////////////////////得实网页模板编辑 websocket 通讯组件，请勿擅自修改本文件内容！！！////////////////////////////////////////////////////

var ds_res = "";
var WebsocketSever = "noble-print:7999";
var t1=null;//废除
var t2=null//废除
var t3=null;
var lastHeartBeat = null;//废除
var flag =0; //当前调用状态：0：未调用，1：调用中（等待），2：成功调用，3：超时
var flagConment=null;//当前状态的任务信息
var currentJob=null;
var reqQueue=new Array();//请求队列
var processQueue=new Array();//处理队列
var resQueue=new Array();//结果队列
var seq = 0;//包序列号
var timebase = 0;
var StatusMachineSpeed = 1;//废除
var hooker_packinfo = null;
var g_invoke_result = null;
var iterator = null;
var StatusMachine_running =false;
function closeMe()
{
	window.opener=null;
	window.open('','_self');
	window.close();
}
function StatusMachine()
{
	if(StatusMachine_running)
		return;
	StatusMachine_running = true;
	if(0==flag)
	{
		ds_res = "";
		if(reqQueue.length!=0)
		{
			currentJob = reqQueue.pop();
			processQueue.unshift(currentJob);
			var callback = currentJob.CALLBACK[0];
			delete currentJob["CALLBACK"];			//服务器不需要回调函数信息，删除之
			ds_sendToPrinter(JSON.stringify(currentJob));
			currentJob.CALLBACK = new Array;
			currentJob.CALLBACK[0] = callback;
			timebase = Date.now();
			flag = 1;
		}
	}
	else if(1==flag)
	{
		var packtype = currentJob.PackType;
		var overtime = packtype==10?1500:(packtype==11?60000:1000);
		if(Date.now()-timebase>overtime)
			flag = 3;
		if(ds_res!="")
			flag = 2;
		var o = {"RtnCode":-1002,"Remarks":currentJob.ReqInfo.FunName,"SEQ":currentJob.SEQ};
		flagConment = o;
	}
	else if(2==flag)
	{
		flag = 0;
		var o =eval('(' + ds_res + ')');
		resQueue.unshift(o);
		for(var i = 0; i < processQueue.length; i++)
		{
			var obj = processQueue[i];
			if(obj.ReqInfo.FunName == o.Remarks && obj.SEQ==o.SEQ)
			{
				processQueue.splice(i, 1);
				break;
			}
		}
		currentJob = null;
		flagConment = o;
		var callback = obj.CALLBACK[0];
		if(callback!=null)
		{
			window.setTimeout(callback(o),1);
		}
	}
	else if(3==flag)
	{
		flag = 0;var obj = null;
		var o = {"RtnCode":-1003,"Remarks":currentJob.ReqInfo.FunName,"SEQ":currentJob.SEQ};
		for(var i = 0; i < processQueue.length; i++)
		{
			var obj = processQueue[i];
			if(obj.ReqInfo.FunName == o.Remarks && obj.SEQ==o.SEQ)
			{
				obj = processQueue.splice(i, 1)[0];
				break;
			}
		}
		//resQueue.unshift(o);
		currentJob = null;
		flagConment = o;
		try{
			var callback = obj.CALLBACK[0];
			if(callback!=null)
			{
				window.setTimeout(callback(o),1);
			}
		}
		catch(e)
		{

		}
	}
	StatusMachine_running =false;
}

function ConnectionTest()
{
	hooker_packinfo = {"PackType":12,"ReqInfo":{"FunName":"InvalidFunction","Parameters":[]},"SEQ":seq,"CALLBACK":[]};
}
var websocket=null;
var FirstTime = true;
var serviceRunning = false;
var t_statusmachine = null;
var t_connect = null;
var s_requestOk = false;

function InitService()
{
	s_requestOk = false;
	serviceRunning = false;
	if(FirstTime)
	{
		WebsocketSever = arguments[0];
		FirstTime = false;
		t_statusmachine = window.setInterval(StatusMachine,5);
	}
	var pt = "ws://";
	try{
		if ("WebSocket" in window) {
			websocket = new WebSocket(pt+WebsocketSever);
		}else if ("MozWebSocket" in window) {
			websocket = new MozWebSocket(pt+WebsocketSever);
		} else {
			alert("当前浏览器不支持WebSocket");
			//closeMe();
			return;
		}
	}
	catch(e)
	{
		//alert("创建WebSocket失败");
		return false;
	}

	s_requestOk = true;

	websocket.onopen = function(evt) {
		if(t_connect != null)
		{
			window.clearTimeout(t_connect);
			t_connect = null;
		}
		serviceRunning = true;
		StatusMachine_running = false;

		KeepAlive(1);
	};

	websocket.onmessage = function(evt) {
		var o = msgCheck(evt.data)?eval('(' + evt.data + ')'):Object.create(Object.prototype);
		if(o.hasOwnProperty('Remarks')){
			var str = o.Remarks;
			if(str != "KeepAlive")
			{
				console.log("websocket onmessage:"+evt.data);
			}
			ds_res = evt.data;
		}
	};

	websocket.onerror = function(evt) {
		//console.log("websocket err!");
		//alert("websocket.onerror");
		websocket.close();
		if(currentJob!=null){
			var s = {"RtnCode":-1004,"Remarks":currentJob.ReqInfo.FunName,"SEQ":currentJob.SEQ};
			ds_res = JSON.stringify(s);
		}

		serviceRunning = false;
		KeepAlive(0);
		websocket = null;
		//t_connect = window.setTimeout(InitService(WebsocketSever),1000);
	};

	websocket.onclose = function()
	{
		//console.log("websocket close!");
		//websocket = null;
		//alert("websocket close!");
		serviceRunning = false;
		KeepAlive(0);
		websocket = null;
		t_connect = window.setTimeout(InitService(WebsocketSever),1000);
	};
}

function msgCheck(str)
{
		if(typeof str == 'string'){
			try{
	    		var obj = JSON.parse(str);
	    		if(typeof obj == 'object' && obj){
		    		return true;
			    }else{
			    	return false;
			    }
	    	}catch(e){
	    		return false;
	    	}
		}

}

function KeepAlive(s)
{
	if(s==1)
	{
		if(t3 != null)
			window.clearInterval(t3);
		t3 = window.setInterval(__KeepAlive,3000);
	}
	else if(s == 0)
	{
		if(t3 != null)
			window.clearInterval(t3);
	}
	function __KeepAlive(){
		hooker_packinfo = {"PackType":13,"ReqInfo":{"FunName":"KeepAlive","Parameters":[]},"SEQ":seq,"CALLBACK":[]};
		Invoke("KeepAlive");
	}
}

function Invoke()
{
	if(arguments.length==0){//console.log("The paramenter list can not be empty!");return;
	}

	var callback=null;var funname = "";
	var data = hooker_packinfo==null?{"PackType":11,"ReqInfo":{"FunName":"InvalidFunction","Parameters":[]},"SEQ":seq,"CALLBACK":[]}:hooker_packinfo;
	hooker_packinfo = null;
	var parlen = 0;var obj=null;
	if(typeof arguments[0]!="object")
	{
		funname = arguments[0]+"";
		obj = new Array;
		for(var i = 1; i< arguments.length; i++)
			obj[i-1] = arguments[i];
	}
	else
	{
		obj = arguments[0];
		funname=obj.callee+"";
		funname = funname.substring(funname.indexOf (" ")+1,funname.indexOf ("("));
	}
	data.ReqInfo.FunName = funname;
	parlen = obj.length;
	if(parlen>0)
	{
		var tempCallback = obj[parlen-1];
		if(typeof tempCallback == "function")
		{
			callback = obj[parlen-1];
			parlen=parlen-1;
		}
		for( var i = 0; i < parlen; i++ )
		{
			data.ReqInfo.Parameters[i]=obj[i];
		}
	}

	data.SEQ = seq;
	seq++;
	//if(data.ReqInfo.FunName=="web_DSEnumPrinter")alert("xcvbbbnn"+JSON.stringify(currentJob));
	data.CALLBACK[0]=callback;
	reqQueue.unshift(data);

}

function ds_sendToPrinter(sdata)
{
	var obj = JSON.parse(sdata);
	if(JSON.parse(sdata).PackType!=13)
	{	console.log("websocket send:"+sdata);}
	if(serviceRunning && t_statusmachine!=null)
		websocket.send(sdata);
	else
	{
		var s = {"RtnCode":-1005,"Remarks":obj.ReqInfo.FunName,"SEQ":obj.SEQ};
		ds_res = JSON.stringify(s);
	}
}

function ds_isConnectOn()
{
	return serviceRunning;
}

function Sleep(timeout, cb) {
    var T = Date.now();
    innerSleep();
    function innerSleep() {
        if (serviceRunning) {
            cb(serviceRunning);
            return;
        }
        if (Date.now() - T < timeout) {
            window.setTimeout(innerSleep, 100);
        }
        else
            cb(serviceRunning);
    }
}
